package com.fenqing.leetcode.code.t700_800;

import com.fenqing.annotations.DesignClass;
import com.fenqing.core.design.DesignTopic;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author fenqing
 */
public class Topic706 extends DesignTopic {
    public Topic706() {
        super(
                """
                        ["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
                        """, """
                        [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
                        """);
    }

    public static void main(String[] args) {
        Topic706 topic706 = new Topic706();
        System.out.println("""
                [null, null, null, 1, -1, null, 1, null, -1]
                """);
        System.out.println(topic706.run());
    }

    @DesignClass
    public static class MyHashMap {
        final static int length = 10000;
        List<int[]>[] hash;

        public MyHashMap() {
            hash = new List[length];
            for (int i = 0; i < length; i++) {
                hash[i] = new LinkedList<>();
            }
        }

        public void put(int key, int value) {
            int index = hash(key);
            List<int[]> hash1 = hash[index];
            for (int[] next : hash1) {
                if (next[0] == key) {
                    next[1] = value;
                    return;
                }
            }
            hash1.add(new int[]{key, value});
        }

        public int get(int key) {
            int index = hash(key);
            List<int[]> hash1 = hash[index];
            for (int[] next : hash1) {
                if (next[0] == key) {
                    return next[1];
                }
            }
            return -1;
        }

        public void remove(int key) {
            int index = hash(key);
            List<int[]> hash1 = hash[index];
            Iterator<int[]> iterator = hash1.iterator();
            while (iterator.hasNext()) {
                int[] next = iterator.next();
                if (next[0] == key) {
                    iterator.remove();
                    return;
                }
            }
        }

        int hash(int key){
            return key % length;
        }
    }
}
